import React from 'react';
import { flowApi } from 'js/api/flow';
import { timeData } from 'js/core/timeData';
import echarts from 'js/lib/echarts';
import { DatePicker } from 'antd-mobile';
import moment from 'moment';
import SelectTimeType from 'views/component/selectTimeType/selectTimeType';
import SelectTitle from 'views/component/selectTitle/selectTitle';
import { SubViewLink } from 'views/component/subViewLink/subViewLink';
import api from 'js/api/index';
import SelectRadioItem from 'views/component/radioOne/radio';
import './flowFace.scss';
import { i18n } from 'js/core/i18n';

class FaceReturningCustomerAgeTwo extends React.Component {
  constructor() {
    super()
    this.state = {
      data: null,
      timeType: 'day',
      loading: true
    }
  }
  componentDidMount() {
    let time = timeData.getTimeRange('day');
    this.query = {
      ShopID: this.props.id,
      timeType: 'day',
      start: time.start,
      end: time.end,
    }
    this.getData();
  }
  getData = () => {
    if (this.chart1) {
      this.chart1.dispose();
    }
    this.setState({ loading: true })
    this.query.ShopID = this.props.id;
    api('/FlowFace/FaceReturningCustomerAgeTwo', this.query).then(data => {
      this.setState({ loading: false })
      let cdata = data.data;
      let option1 = {
        textStyle: { fontSize: window.chatFontSize },
        grid: {
          left: '9%',
          top: '10%',
          width: '82%',
          height: '80%',
        },
        xAxis: {
          type: 'category',
          data: cdata.customer.dataX,
          boundaryGap: false,
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: true, lineStyle: { color: '#ccc' } },
          axisLabel: { show: true, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        yAxis: {
          type: 'value',
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: true, lineStyle: { color: '#ccc' } },
          axisLabel: { show: false, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        dataZoom: {
          type: 'inside',
          zoomLock: true,
          startValue: cdata.customer.dataX.length - 7,
          endValue: cdata.customer.dataX.length - 1
        },
        series: {
          type: 'line',
          label: { normal: { show: true, color: '#333' } },
          lineStyle: { normal: { color: '#BFB1F7' } },
          data: cdata.customer.dataY
        }
      }
      this.chart1 = echarts.init(this.refs.chart1);
      this.chart1.setOption(option1);
      let age = cdata.age.dataType.map((item, index) => {
        return { name: item, value: cdata.age.dataChart[index] }
      })
      let option2 = {
        textStyle: { fontSize: window.chatFontSize },
        series: [
          {
            type: 'pie',
            radius: ['20%', '40%'],
            data: age,
            labelLine: {
              normal: {
                length: 10,
                length2: 10,
              }
            },
            label: {
              normal: {
                formatter: '{b}\n{c}'
              }
            }
          }
        ]
      };

      this.chart2 = echarts.init(this.refs.chart2);
      this.chart2.setOption(option2);
    });
  }
  timeTypeOnChange = (value, time) => {
    this.query.timeType = value;
    this.query.start = time.start;
    this.query.end = time.end;
    this.setState({ timeType: value })
    this.getData();
  }
  open = () => {
    this.setState({ openStatus: !this.state.openStatus }, () => {
      this.chart2.resize()
    })
  }
  render() {
    let { timeType, openStatus } = this.state;
    return <div className="box pb25">
      <div className="boxHead flex-vcenter">
        <div className="title">{i18n.get("回头客分析")}</div>
        <div className="unitText flex-g-1">({i18n.get("单位:人次")})</div>
        <div className="open flex-center" onClick={this.open}>{openStatus ? i18n.get('收起') : i18n.get('展开')}<div className={openStatus ? "close_icon" : "open_icon"}></div></div>
      </div>
      <SelectTimeType value={timeType} onChange={this.timeTypeOnChange} className="mb25" />
      <div className="chart" ref="chart1"></div>
      <div className={openStatus ? "" : "hide"}>
        <div className="chartTitle pt25 mb15">{i18n.get("回头客年龄分析")}</div>
        <div className="chart" ref="chart2"></div>
      </div>
    </div>
  }
}

class FlowHotSpotTimeTopThree extends React.Component {
  constructor() {
    super()
    this.state = {
      data: null,
      timeType: 'day',
      year: moment().year(),
      loading: true,
      counttype: 1
    }
  }
  componentDidMount() {
    this.query = {
      ShopID: this.props.id,
      year: moment().year(),
      timeType: 'day',
      counttype: 1,
    }
    this.getData()
  }
  getData = () => {
    if (this.chart) {
      this.chart.dispose();
    }
    if (this.storeChart) {
      this.storeChart.dispose();
    }
    this.setState({ loading: true })
    this.query.ShopID = this.props.id;
    api('/FlowFace/FlowHotSpotTimeTopThree', this.query).then(data => {
      this.setState({ loading: false })
      let cdata = data.data;
      this.chart = echarts.init(this.refs.chart);
      cdata.dataX = cdata.dataX.map(item => {
        return item.replace('-', '-\n');
      });
      let option = {
        textStyle: { fontSize: window.chatFontSize },
        grid: {
          left: '9%',
          top: '10%',
          width: '82%',
          height: '72%',
        },
        xAxis: {
          type: 'category',
          data: cdata.dataX,
          boundaryGap: false,
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: true, lineStyle: { color: '#ccc' } },
          axisLabel: { show: true, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        yAxis: {
          type: 'value',
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: true, lineStyle: { color: '#ccc' } },
          axisLabel: { show: false, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        dataZoom: {
          type: 'inside',
          zoomLock: true,
          startValue: cdata.dataX.length - 7,
          endValue: cdata.dataX.length - 1
        },
        series: {
          type: 'line',
          label: { normal: { show: true, color: '#333' } },
          lineStyle: { normal: { color: '#BFB1F7' } },
          data: cdata.dataY
        }
      }
      this.chart.setOption(option);
      this.storeChart = echarts.init(this.refs.pChart);
      let storeDataX = [], storeSeriesData = [];
      let color = ['#83C8FF', '#BEB1F9', '#FFCDB2'];
      data.data.top.forEach((item, index) => {
        storeDataX.unshift(item.desc.replace('-', '-\n'));
        storeSeriesData.unshift({
          value: item.CountData,
          label: { normal: { show: true, position: 'right', color: '#ccc' } },
          itemStyle: {
            normal: { color: color[index] }
          }
        });
      });
      let option1 = {
        textStyle: { fontSize: window.chatFontSize },
        grid: {
          left: '15%',
          right: '17%',
          bottom: '3%',
          top: '5%'
        },
        yAxis: {
          type: 'category',
          data: storeDataX,
          boundaryGap: true,
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: false, lineStyle: { color: '#ccc' } },
          axisLabel: { show: true, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        xAxis: {
          type: 'value',
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: false, lineStyle: { color: '#ccc' } },
          axisLabel: { show: false, color: '#333', interval: 0 },
          axisLine: { show: false, lineStyle: { color: '#ccc' } },
        },
        series: [{
          type: 'bar',
          data: storeSeriesData
        }]
      }
      this.storeChart.setOption(option1);
    });
  }
  timeTypeOnChange = (value, time) => {
    this.query.timeType = value;
    this.setState({ timeType: value })
    this.getData();
  }
  open = () => {
    this.setState({ openStatus: !this.state.openStatus }, () => {
      this.storeChart.resize()
    })
  }
  yearOnChange = (date) => {
    this.query.year = moment(date).year();
    this.setState({ year: moment(date).year() }, () => {
      this.getData()
    })
  }
  sexOnchange = (value) => {
    this.query.counttype = value;
    this.setState({ counttype: value })
    this.getData();
  }
  render() {
    let { timeType, openStatus, year, loading, counttype } = this.state;
    let selectTimeTypeData = [{ name: i18n.get('时'), value: 'hour' }, { name: i18n.get('日'), value: 'day' }, { name: i18n.get('月'), value: 'month' }];
    return <div className="FlowHotSpotTimeTopThree box pb25">
      <div className="boxHead flex-vcenter">
        <div className="title">{i18n.get("热点时段分析")}</div>
        <div className="unitText flex-g-1">({i18n.get("单位:人次")})</div>
        <div className="open flex-center" onClick={this.open}>{openStatus ? i18n.get('收起') : i18n.get('展开')}<div className={openStatus ? "close_icon" : "open_icon"}></div></div>
      </div>
      <SelectTimeType value={timeType} data={selectTimeTypeData} onChange={this.timeTypeOnChange} className="mb25" />
      <DatePicker extra={i18n.get("请选择")} locale={{ DatePickerLocale: { year: i18n.get("年"), month: i18n.get("月"), day: i18n.get("日"), hour: i18n.get("时"), minute: i18n.get("分") } }} okText={i18n.get("确定")} dismissText={i18n.get("取消")} mode="year" value={new Date((new Date()).setFullYear(year))} onChange={this.yearOnChange}>
        <div className="selectYear flex-center">
          {i18n.get('年份选择')}:{year}
        </div>
      </DatePicker>
      <div className="chart" ref="chart">
        {loading && <div className="loading"></div>}
      </div>
      <SelectRadioItem data={[{ name: i18n.get('男顾客'), id: 1 }, { name: i18n.get('女顾客'), id: 0 }, { name: i18n.get('回头客'), id: 2 }]} value={counttype} onChange={this.sexOnchange} />
      <div className={openStatus ? "" : "hide"}>
        <div className="chartTitle pt25">{i18n.get("热点时段TOP3")}</div>
        <div className="chart chart1" ref="pChart">
          {loading && <div className="loading"></div>}
        </div>
      </div>
    </div>
  }
}

class FlowTrendChartSameRing extends React.Component {
  constructor() {
    super()
    this.state = {
      flowTypeDWMYData: null,
      timeType: 'day',
      sex: 1,
      openStatus: false,
      loading: false
    }
  }
  componentDidMount() {
    let time = timeData.getTimeRange('day');
    this.query = {
      ShopID: this.props.id,
      timeType: 'day',
      start: time.start,
      sex: 1,
      end: time.end,
    }
    this.getData()
  }
  getData = () => {
    if (this.chart) {
      this.chart.dispose();
    }
    if (this.storeChart) {
      this.storeChart.dispose();
    }
    this.setState({ loading: true })
    this.query.ShopID = this.props.id;
    api('/FlowFace/FlowTrendChartSameRing', this.query).then(data => {
      this.setState({ loading: false })
      let cdata = data.data;
      this.chart = echarts.init(this.refs.chart);
      let option = {
        textStyle: { fontSize: window.chatFontSize },
        grid: {
          left: '9%',
          top: '10%',
          width: '82%',
          height: '80%',
        },
        xAxis: {
          type: 'category',
          data: cdata.dataX,
          boundaryGap: false,
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: true, lineStyle: { color: '#ccc' } },
          axisLabel: { show: true, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        yAxis: {
          type: 'value',
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: true, lineStyle: { color: '#ccc' } },
          axisLabel: { show: false, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        dataZoom: {
          type: 'inside',
          zoomLock: true,
          startValue: cdata.dataX.length - 7,
          endValue: cdata.dataX.length - 1
        },
        series: {
          type: 'line',
          label: { normal: { show: true, color: '#333' } },
          lineStyle: { normal: { color: '#BFB1F7' } },
          data: cdata.dataY
        }
      }
      this.chart.setOption(option);
      this.storeChart = echarts.init(this.refs.pChart);
      cdata.dataMom = cdata.dataMom.map(item => {
        return {
          value: Number(item),
          label: {
            normal: {
              show: true,
              formatter: '{c}%',
              position: Number(item) >= 0 ? 'top' : 'bottom'
            }
          }
        };
      });
      cdata.dataYoy = cdata.dataYoy.map(item => {
        return {
          value: Number(item),
          label: {
            normal: {
              show: true,
              formatter: '{c}%',
              position: Number(item) >= 0 ? 'top' : 'bottom'
            }
          }
        };
      });
      let option1 = {
        textStyle: { fontSize: window.chatFontSize },
        grid: {
          left: '9%',
          top: '18%',
          width: '82%',
          height: '63%',
        },
        legend: {
          data: [i18n.get('环比'), i18n.get('同比')],
        },
        color: ['#83C8FF', '#BDB0F8'],
        xAxis: {
          type: 'category',
          data: cdata.dataX,
          boundaryGap: true,
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: false, lineStyle: { color: '#ccc' } },
          axisLabel: { show: true, color: '#333', interval: 0, margin: 20 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        yAxis: {
          type: 'value',
          axisTick: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { show: false, lineStyle: { color: '#ccc' } },
          axisLabel: { show: false, color: '#333', interval: 0 },
          axisLine: { show: true, lineStyle: { color: '#ccc' } },
        },
        dataZoom: {
          type: 'inside',
          zoomLock: true,
          startValue: cdata.dataX.length - 5,
          endValue: cdata.dataX.length - 1
        },
        series: [{
          type: 'bar',
          name: i18n.get('环比'),
          data: cdata.dataMom
        }, {
          type: 'bar',
          name: i18n.get('同比'),
          data: cdata.dataYoy
        }]
      }
      this.storeChart.setOption(option1);
    });
  }
  timeTypeOnChange = (value, time) => {
    this.query.timeType = value;
    this.query.start = time.start;
    this.query.end = time.end;

    this.setState({ timeType: value })
    this.getData();
  }
  open = () => {
    this.setState({ openStatus: !this.state.openStatus }, () => {
      this.storeChart.resize()
    })
  }
  sexOnchange = (value) => {
    this.query.sex = value;
    this.setState({ sex: value })
    this.getData();
  }
  render() {
    let { timeType, openStatus, sex, loading } = this.state;
    return <div className="box">
      <div className="boxHead flex-vcenter">
        <div className="title">{i18n.get("顾客趋势分析")}</div>
        <div className="unitText flex-g-1"></div>
        <div className="open flex-center" onClick={this.open}>{openStatus ? i18n.get('收起') : i18n.get('展开')}<div className={openStatus ? "close_icon" : "open_icon"}></div></div>
      </div>
      <SelectTimeType value={timeType} onChange={this.timeTypeOnChange} className="mb25" />
      <div className="chart" ref="chart">
        {loading && <div className="loading"></div>}
      </div>
      <SelectRadioItem data={[{ name: i18n.get('男顾客'), id: 1 }, { name: i18n.get('女顾客'), id: 0 }]} value={sex} onChange={this.sexOnchange} />
      <div className={openStatus ? "pb25" : "hide"}>
        <div className="chartTitle">{i18n.get("顾客同环比图")}</div>
        <div className="chart" ref="pChart">
          {loading && <div className="loading"></div>}
        </div>
      </div>
    </div>
  }
}

class FaceSexAge extends React.Component {
  constructor() {
    super()
    this.state = {
      data: null,
      timeType: 'day',
      sex: {},
      openStatus: false,
    }
  }
  componentDidMount() {
    let time = timeData.getTimeRange('day');
    this.query = {
      ShopID: this.props.id,
      timeType: 'day',
      start: time.start,
      end: time.end,
    }
    this.getData()
  }
  getData = () => {
    if (this.chart) {
      this.chart.dispose();
    }
    this.setState({ loading: true })
    this.query.ShopID = this.props.id;
    api('/FlowFace/FaceSexAge', this.query).then(data => {
      this.setState({ loading: false })
      data = data.data;
      this.setState({ sex: data.sex })
      let option = {
        textStyle: { fontSize: window.chatFontSize },
        color: ['#aaf4bd', '#81c5ff', '#fed871', '#ffa9a9', '#D35F44'],
        series: [
          {
            type: 'pie',
            radius: ['20%', '40%'],
            data: data.age,
            labelLine: {
              normal: {
                length: 10,
                length2: 10,
              }
            },
            label: {
              normal: {
                formatter: '{b}\n{c}'
              }
            }
          }
        ]
      };
      this.chart = echarts.init(this.refs.chart);
      this.chart.setOption(option);
    });
  }
  timeTypeOnChange = (value, time) => {

    this.query.timeType = value;
    this.query.start = time.start;
    this.query.end = time.end;
    if (value === 'month') {
      this.query.start = moment(time.start).format('YYYY-MM-01');
      this.query.end = moment(time.end).format('YYYY-MM-01');
    }
    this.setState({ timeType: value }, () => {
      this.getData();
    })

  }
  open = () => {
    this.setState({ openStatus: !this.state.openStatus }, () => {
      this.chart.resize()
    })
  }
  render() {
    let { sex, timeType, openStatus, loading } = this.state;
    return <div className="box">
      <div className="boxHead flex-vcenter">
        <div className="title">{i18n.get("顾客属性分析")}</div>
        <div className="unitText flex-g-1"></div>
        <div className="open flex-center" onClick={this.open}>{openStatus ? i18n.get('收起') : i18n.get('展开')}<div className={openStatus ? "close_icon" : "open_icon"}></div></div>
      </div>
      <SelectTimeType value={timeType} onChange={this.timeTypeOnChange} className="mb25" />
      <div className="flex-center pb25">
        <div className="flex-g-1 flex-col-center">
          <div className="icon_girl"></div>
          <div className="mt10"> {i18n.get("女生占比")}<span className="ml20" style={{ color: '#41C0C1' }}>{sex.girlScale}</span></div>
        </div>
        <div className="flex-g-1  flex-col-center">
          <div className="icon_boy"></div>
          <div className="mt10">{i18n.get("男生占比")}<span className="ml20" style={{ color: '#41C0C1' }}>{sex.boyScale}</span></div>
        </div>
      </div>
      <div className={openStatus ? "" : "hide"}>
        <div className="chartTitle">{i18n.get("年龄分布")}</div>
        <div className="chart" ref="chart">
          {loading && <div className="loading"></div>}
        </div>
      </div>
    </div>
  }
}

class Main extends React.Component {
  constructor() {
    super()
    this.state = {
      timetype: 1,
      shop: null,
    }
  }
  componentDidMount() {
    this.ShopList();
  }
  ShopList = () => {
    api('/BaseSet/ShopList').then(data => {
      this.setState({ shop: data.data[0] })
    });
  }
  shopNameOnChange = (shopInfo) => {
    this.setState({ shop: shopInfo }, () => {
      this.refs.faceSexAge.getData();
      this.refs.flowTrendChartSameRing.getData();
      this.refs.flowHotSpotTimeTopThree.getData();
      this.refs.faceReturningCustomerAgeTwo.getData();
    })
  }
  render() {
    let { shop } = this.state;
    let node;
    if (shop) {
      node = <div>
        <FaceSexAge id={shop.ShopId} ref="faceSexAge" />
        <FlowTrendChartSameRing id={shop.ShopId} ref="flowTrendChartSameRing" />
        <FlowHotSpotTimeTopThree id={shop.ShopId} ref="flowHotSpotTimeTopThree" />
        <FaceReturningCustomerAgeTwo id={shop.ShopId} ref="faceReturningCustomerAgeTwo" />
      </div>
    }
    return <div id="flowFace">
      <div className="device-container">
        <div className="deviceItem device-border flex-vcenter">
          <SelectTitle classStyle="name">{i18n.get("选择店铺")}</SelectTitle>
          <SubViewLink moduleName="shopSearch" className="flex-g-1 text-right deviceItemContent" title={i18n.get('选择店铺')} modelData={{ onChange: this.shopNameOnChange }}>
            {shop ? shop.ShopName : <div style={{ color: '#909090' }}>{i18n.get('选择店铺')}</div>}
          </SubViewLink>
        </div>
      </div>
      {node}
    </div>
  }
}


export default Main;